import React, {  useEffect, useState, useContext, useMemo } from 'react'
// 导入axios请求
import apiServe, { https } from '../../api/apiServer'
// 样式导入
import './index.scss'
import { Context } from '../../App'
import { useHistory } from 'react-router-dom'

export default function List ()  {
    const [newsList, setnewsList] = useState([])
    const app = useContext(Context)
	// 路由hooks
	const history = useHistory()
	useEffect( async () => {
	    let obj = {
			cityId: 'AREA|dbf46d32-7e76-1196',
			start: 1,
			end: 20,
		}
		let list = await apiServe.getHouses(obj)
		setnewsList(list.body.list)
	}, [])
	const goHouseInfo = code => {
		return () => {
			history.push({
				pathname: '/houseInfo',
				state: { code: code },
			})
		}
    }
    // 添加
    function add(code) {
        return () => {
            app.dispatch({
				type: 'add',
				data: code,
			})
        }
    }
    // 删除
    function dele (code) {
        return () => {
            app.dispatch({
				type: 'dele',
				data: code,
			})
        }
    }
    // 过滤计算
    function filterCode (code) {
        let count = 0
        app.state.forEach(item => {
            if (item === code) {
                count = count + 1
            }
        })
        return count
    }
	return (
		<div className='news'>
			{
					newsList.map((item, index) => {
						return (
							<div className='news-item' key={index} onClick={goHouseInfo(item.houseCode)}>
								<div className='imgwrap'>
									<img className='img' src={`${https}${item.houseImg}`} alt='' />
								</div>
								<div className='content' direction='column' justify='between'>
									<h3 className='titles'>{item.title}</h3>
									<p>{item.desc}</p>
									<div
										className='info'
										justify='between'
										onClick={e => {
											e.stopPropagation()
										}}
									>
										<span className='price'>
											<span className='big'>{item.price}</span>元/月
										</span>
										<div className='bjq'>
											<div onClick={dele(item.houseCode)} className='dele br'>
												-
											</div>
											<div className='count br'>{filterCode(item.houseCode)}</div>
											<div onClick={add(item.houseCode)} className='add br'>
												+
											</div>
										</div>
									</div>
								</div>
							</div>
						)
					})}
		</div>
	)
}
